<template>
  <!-- 上传CAD -->
  <div>
    <div style="display: none">
      <input id="fileInputer" type="file" @change="handleFileChange" />
    </div>
    <el-dialog
      v-model="confrimWindowShow"
      width="100%"
      :close-on-click-modal="false"
    >
      <template #footer>
        <span class="dialog-footer">
          <p>{{ progressText }}</p>
          <el-progress :percentage="progressStage * progressValue">
            <span>{{ progressStage }}/4</span>
          </el-progress>
          <p>绘制进度：</p>
          <el-progress :percentage="(layerCount / layerTotal) * 100">
            <span>{{ layerCount }}/{{ layerTotal }}</span>
          </el-progress>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
/*eslint-disable*/
import { getCurrentInstance, onMounted } from "vue";
import pubsub from "pubsub-js";
import { useRouter } from "vue-router";
import axios from "axios";

import message from "@/components/Message/showMessage";
import urlList from "@/store/urlList.json";

export default {
  name: "上传CAD",
  data() {
    return {
      confrimWindowShow: false,
      progressValue: 25,
      progressStage: 0,
      layerTotal: 0,
      layerCount: 0,
      progressText: "准备上传……",
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();

    // 上传是否取消
    let uploadCancel;
    // 路由器
    const router = useRouter();
    // dwg文件名
    let dwgFileName = "";

    onMounted(() => {
      // axios拦截器注册
      setInterceptors();
      setTimeout(() => {
        uploadCancel = true;
        // 进度条显示
        proxy.confrimWindowShow = true;
        // 手动调用点击事件
        document.querySelector("#fileInputer").click();
        // 取消事件注册
        window.addEventListener(
          "focus",
          () => {
            CancelHandler();
          },
          { once: true }
        );
      }, 300);
    });

    //  axios拦截器设置
    function setInterceptors() {
      // 添加请求拦截器
      axios.interceptors.request.use(
        function (config) {
          switch (config.url) {
            case urlList.cadURL:
              proxy.progressStage = 1;
              proxy.progressText = "数据上传中……";
              break;
            case urlList.serverURL + "uploadGeoJson":
              proxy.progressStage = 3;
              proxy.progressText = "数据存储中……";
              break;
            default:
              break;
          }
          return config;
        },
        function (error) {
          // 对请求错误做些什么
          message("数据上传失败", "error");
          return Promise.reject(error);
        }
      );

      // 添加响应拦截器
      axios.interceptors.response.use(
        function (response) {
          switch (response.config.url) {
            case urlList.cadURL:
              proxy.progressStage = 2;
              proxy.progressText = "数据解析中……";
              break;
            case urlList.serverURL + "uploadGeoJson":
              proxy.progressStage = 4;
              proxy.progressText = "图层绘制中……";
              break;
            default:
              break;
          }

          return response;
        },
        function (error) {
          if (!error.response) {
            message("服务器未响应", "error", 5000);
          }
          return Promise.reject(error);
        }
      );
    }

    // 取消处理器
    function CancelHandler() {
      setTimeout(() => {
        if (uploadCancel) {
          router.push({
            path: "/mapLayout",
          });
        }
      }, 100);
    }

    // 读取文件
    function handleFileChange() {
      uploadCancel = false;
      // 数据类型限制
      if (!typeControl(event)) return;
      // 由服务器将dwg处理成geoJson
      uploadData(event)
        .then((res) => {
          // 数据处理
          handleData(res.data.data.features);
        })
        .catch((err) => {
          errHanlder("服务器出错：" + err);
        });
    }

    // 数据类型限制
    function typeControl() {
      const file = event.target.files[0];
      // 读取dwg文件名
      dwgFileName = file.name;
      // 仅支持上传.dxf文件
      if (file.name.split(".")[file.name.split(".").length - 1] != "dwg") {
        message("仅支持上传.dwg文件，请重试！", "error");
        setTimeout(() => {
          router.push({
            path: "/mapLayout",
          });
        }, 1500);
        return false;
      }
      return true;
    }

    // 数据上传至服务器
    function uploadData(event) {
      // 数据上传准备
      const formData = new FormData();
      formData.append("file", event.target.files[0]);
      return axios.post(urlList.cadURL, formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });
    }

    // 数据处理与分发
    function handleData(geoJson) {
      console.log(geoJson);
      let layerJson;
      // 图层区分
      layerDistinction(geoJson)
        // GeoJons存至数据库
        .then((res) => {
          layerJson = res;
          return geoJsonToDatabase(res);
        })
        // 图层绘制
        .then((res) => {
          res.data.code === 1
            ? message(res.data.msg)
            : errHanlder("数据上传失败：" + res.data.msg);
          geoJsonDraw(layerJson);
        });
    }

    // GeoJson图层区分
    function layerDistinction(geoJson) {
      return new Promise((res, rej) => {
        res(geoJson);
      });
    }

    // GeoJons存至数据库
    function geoJsonToDatabase(geoJson) {
      return axios({
        method: "post",
        url: urlList.serverURL + "uploadGeoJson",
        data: {
          data: JSON.stringify(geoJson),
          id: "timeStamp_" + new Date().getTime(),
          name: dwgFileName,
        },
      });
    }

    // GeoJson图层绘制
    function geoJsonDraw(geoJson) {
      //   console.log(geoJson);
      // 图层总数录入
      proxy.layerTotal = geoJson.length;
      //  遍历绘制
      geoJson.forEach((feature) => {
        proxy.layerCount++;
        let pointList = [];
        feature.geometry.coordinates.forEach((element) => {
          pointList.push(element.reverse());
        });
        // 颜色
        let color = feature.properties.color;
        color = color.substring(0, color.length - 2);
        // 线宽
        let weight = feature.properties.style.split(":")[2].split("px")[0];
        // 绘制
        L.polyline(pointList, { color, weight }).addTo(_map);
      });
    }

    // 报错处理器
    function errHanlder(errText) {
      console.log(errText);
      message(errText, "error", 5000);
    //   setTimeout(() => {
    //     router.push({
    //       path: "/mapLayout",
    //     });
    //   }, 5000);
    }

    return {
      handleFileChange,
    };
  },
};
</script>

<style lang="less" scoped>
.dialog-footer {
  text-align: center;
  > p {
    text-align: left;
    font-size: 120%;
    margin: 5% 0;
  }
}
</style>